#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/4/29 1:51 下午
# @Author  : adam

import requests
import json
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")


LEANCLOUD_APP_ID="BL0eDKFkzB8qmoWMYFxdCWFf-gzGzoHsz"
LEANCLOUD_APP_MASTER_KEY="TRqoR7Ryvl0FgExgd0965WUr"


def get_message(chat_room_id, payload):
    header_dict = {'X-LC-Id': LEANCLOUD_APP_ID,
                   "X-LC-Key": LEANCLOUD_APP_MASTER_KEY + ",master",
                   'Content-Type': "application/json"}
    url = 'https://leancloud.youinsh.com/1.2/rtm/chatrooms/{}/messages'.format(chat_room_id)

    response = requests.get(url, headers=header_dict, params=payload)
    response.encoding = 'utf-8'
    response_data = response.json()
    return response_data


def get_msg_info():

    chat_room_id='608a4c1a80e90140695a16e9'
    payload = {"limit": 1000, "reversed": True}
    response_data = get_message(chat_room_id, payload)

    # mycol=con_mongo()
    # mycol.insert_many(response_data)
    for i in response_data:
        data = i["data"]
        try:
            data_json = json.loads(data)
            print(data_json)
            if "_lctext" in data_json.keys():
                _lctext = data_json["_lctext"]
                print(_lctext)

        except Exception as e:
            continue


def con_mongo():
    mydb = myclient["test"]
    # collist = mydb.list_collection_names()
    mycol = mydb["saas_357"]
    return mycol

    # mylist = [
    #     {"_id": 1, "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com"},
    #     {"_id": 2, "name": "QQ", "alexa": "101", "url": "https://www.qq.com"},
    #     {"_id": 3, "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com"},
    #     {"_id": 4, "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com"},
    #     {"name": "Github", "alexa": "109", "url": "https://www.github.com"}
    # ]
    #
    # y = mycol.insert_many(mylist)
    # print(y.inserted_ids)


get_msg_info()